require 'hpricot'
require 'open-uri'

class WowHeadItemsFetcher
  
  class << self
    def fetchItem(item)
      
      doc = Hpricot(open("http://www.wowhead.com/?item=" + item.wowlink.to_s))
      parseSingleItemDocument(doc, item)
    end
  
    def parseSingleItemDocument(document, item)
      #item = Item.new
      
      
      
      #wowhead puts all pertinent stuff into javascript
      
      magic = document.search("div.contents/script")[1].children[0].to_s
      lines = magic.scan(/(.*);/)
  
      #the first line has the icon name
      item.iconname = lines[0].to_s.scan(/'(.*?)'/)[1].to_s
      
      #the remainder is a html table for everything else...
      rest = lines[1].to_s.scan(/'(.*?[^\\])'/)[1].to_s
      mini = Hpricot(rest)
      
      #item.wowlink = wowlink
      item.name = mini.search("b[@class=q4]").text
      
      true
    end
    
    def parseItemsList(document)
      if !(document.search("div.contents/h1")[0].children[0].to_s =~ /Search results for/)      
        return nil
      end
    
      magic = document.search("div.contents/script")[0].children[0].to_s
      #Now it gets hard, we need to parse the javascript variables, and we need to do it properly
      #http://www.bigbold.com/snippets/posts/show/2190 may help
      #for now this is simply TODO
      
    end
  end #static methods
end


class AllakhazamItemsFetcher
  
  def parseItemList(document)
    interest = document.search("div[@id=main_body]//table").last
    interest = interst.search("td[@class=dr]")
    interest.each do |element|
    
    end
  
  end

  def fetchSingleItem(wowlink)
    doc = hpricot(open("http://wow.allakhazam.com/db/item.html?source=live;witem=" + wowlink))
    
  end

  #parse a single item document from allakhazam
  def parseSingleItemDocument(document, wowlink)
    item = Item.new
    #This is the magic hpricot path to the interersting part of the allakhazam page
    magic = "div.wowitem/../.."
    interest = document.search(magic)
    imageURL = document.search("img")[0].attributes["src"]
    
    item.wowlink = wowlink
    item.iconname = urlToIcon(imageURL)
    item.name = document.search("span")[0].children[0].to_s    
    item
  end
  
  def urlToIcon(url)
    return url.scan(/\/(.*).png/)[0]
  end
end